import { Token } from "@/types/data";
import { RootThunkAction, LoginFormType, ReqLogin, LoginAction } from "@/types/store";
import request from '@/utils/http'
import { setToken, clearToken } from "@/utils/storage";

// 发送登录请求
export const login = (values: LoginFormType): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.post<ReqLogin>('/authorizations', values)
    console.log('登录后Token返回', res.data.data)
    setToken(res.data.data)
    dispatch({
      type: 'login/token',
      payload: res.data.data
    })
  }
}

// 获取验证码请求
export const getCode = (mobile: string) => {
  return async () => {
    //! 验证码是发送到手机上的，所以不需要更新redux状态，不用再次dispatch
    await request.get(`/sms/codes/${mobile}`)
  }
}

export function logout(): LoginAction {
  clearToken()
  return {
    type: 'login/logout'
  }
}


export function saveToken(token: Token): LoginAction {
  setToken(token)
  return {
    type: 'login/token',
    payload: token
  }
}